package spring.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 使用cglib返回代理对象
 */
public class CglibProxy implements MethodInterceptor {

    Object target;

    Object getProxy(Object target){
        this.target = target;

        Enhancer enhancer = new Enhancer();

        // 设置父类
        enhancer.setSuperclass(target.getClass());
        // 设置回调（这里自己实现了）
        enhancer.setCallback(this);
        // 设置类加载器
        enhancer.setClassLoader(target.getClass().getClassLoader());

        // 生成代理对象
        return enhancer.create();

    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object result = null;

        try {
            // 前置通知
            System.out.println("前置通知");

            // 调用目标类的方法
            result = method.invoke(target, args);

            // 返回通知
            System.out.println("返回通知");
        } catch (InvocationTargetException e) {
            // 异常通知
            System.out.println("异常通知");
            throw new RuntimeException(e);
        } finally {
            System.out.println("后置通知");
        }

        return result;
    }
}
